package com.example.coursedesign.ui.home;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.database.SQLException;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ListView;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.appcompat.app.ActionBar;
import androidx.appcompat.app.AppCompatActivity;

import com.example.coursedesign.R;
import com.example.coursedesign.ui.home.adapter.RemindAdapter;
import com.example.coursedesign.ui.home.dao.mRemindDao;
import com.example.coursedesign.ui.home.entity.mRemind;

import java.util.ArrayList;
import java.util.List;

public class medicineRemind extends AppCompatActivity {
    private ListView listView_reminds;
    private Button button_addRemind;
    private BroadcastReceiver updateReceiver;
    private RemindAdapter remindAdapter; // 保持对适配器的引用

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.medicine_remind);

        // 设置标题栏的标题
        getSupportActionBar().setTitle("吃药提醒");

        // 初始化视图组件
        listView_reminds = findViewById(R.id.listView_reminds);
        button_addRemind = findViewById(R.id.remind);

        // 启用返回按钮
        ActionBar actionBar = getSupportActionBar();
        if (actionBar != null) {
            actionBar.setDisplayHomeAsUpEnabled(true);
            actionBar.setDisplayShowHomeEnabled(true);
        }
        // 注册广播接收器
        updateReceiver = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                if (intent.getAction().equals("com.example.coursedesign.UPDATE_REMIND_LIST")) {
                    new FetchDataAsyncTask().execute();
                }
            }
        };

        // 注册广播
        registerReceiver(updateReceiver, new IntentFilter("com.example.coursedesign.UPDATE_REMIND_LIST"));

        // 初始化提醒列表
        new FetchDataAsyncTask().execute();

        // 添加提醒按钮点击事件
        button_addRemind.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(medicineRemind.this, addRemind.class);
                startActivityForResult(intent, 1); // 启动活动并等待结果
            }
        });

        // 为ListView设置点击事件监听器
        listView_reminds.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                mRemind selectedRemind = (mRemind) parent.getItemAtPosition(position);
                Intent intent = new Intent(medicineRemind.this, addRemind.class);
                intent.putExtra("REMIND_ID", selectedRemind.getId()); // 传递提醒ID
                startActivityForResult(intent, 1); // 启动活动并等待结果
            }
        });
    }

    private void updateRemindList(List<mRemind> remindList) {
        // 过滤掉 status 为 "已服用" 的提醒，并保持原始排序
        List<mRemind> filteredRemindList = new ArrayList<>();
        for (mRemind remind : remindList) {
            if ("未服用".equals(remind.getStatus())) { // 使用 equals 方法比较字符串
                filteredRemindList.add(remind);
            }
        }

        // 如果适配器已经存在，则调用 notifyDataSetChanged 更新视图，否则创建新的适配器
        if (remindAdapter == null) {
            remindAdapter = new RemindAdapter(this, filteredRemindList);
            listView_reminds.setAdapter(remindAdapter);
        } else {
            remindAdapter.setRemindList(filteredRemindList);
            remindAdapter.notifyDataSetChanged(); // 确保更新视图
        }
    }

    public class FetchDataAsyncTask extends AsyncTask<Void, Void, List<mRemind>> {
        @Override
        protected List<mRemind> doInBackground(Void... voids) {
            try {
                mRemindDao remindDao = new mRemindDao();
                List<mRemind> remindList = remindDao.findAll();

                // 对提醒列表按 id 降序排序
                if (remindList != null) {
                    remindList.sort((r1, r2) -> Integer.compare(r2.getId(), r1.getId()));
                }

                return remindList;
            } catch (SQLException | java.sql.SQLException e) {
                e.printStackTrace();
                return null;
            }
        }

        @Override
        protected void onPostExecute(List<mRemind> remindList) {
            if (remindList != null) {
                updateRemindList(remindList);
            } else {
                Toast.makeText(medicineRemind.this, "加载提醒失败", Toast.LENGTH_SHORT).show();
            }
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 1 && resultCode == RESULT_OK) {
            // 当从添加或编辑活动返回时，刷新列表
            if (data != null) {
                long remindId = data.getLongExtra("REMIND_ID", -1);
                if (remindId != -1) {
                    // 如果有特定提醒ID，可以尝试直接更新该条目而不必重新加载全部数据
                    // 这里可以选择性地实现更细粒度的更新逻辑
                }
            }
            // 刷新整个列表（考虑到可能有其他变化）
            new FetchDataAsyncTask().execute();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        // 取消注册广播
        unregisterReceiver(updateReceiver);
    }
    @Override
    public boolean onSupportNavigateUp() {
        setResult(AppCompatActivity.RESULT_OK); // 设置返回结果
        finish(); // 结束当前活动并返回上一个活动
        return true;
    }

    @Override
    public void onBackPressed() {
        setResult(AppCompatActivity.RESULT_OK); // 设置返回结果
        super.onBackPressed(); // 返回上一个 Activity
    }
}